<?php
/**
 * Created by PhpStorm.
 * User: Edward
 * Date: 2019/5/31
 * Time: 13:23
 */

namespace app\admin\controller\user;


use app\admin\BaseController;
use app\admin\model\UserEnterprise;
use app\admin\model\UserFeedback;
use app\api\model\UserToken;
use app\common\controller\UtilCommon;
use app\lib\exception\FailedException;
use app\lib\exception\NotFoundException;
use app\Validate\ActionMustPositiveValidate;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;
use think\Db;
use think\Request;

class User extends BaseController {
    /**
     * 商家首页统计
     * @param Request $request
     */
    public function shopStatistics(Request $request){
        $product_model = new \app\api\model\Product();
        $order_model = new \app\api\model\ProductOrder();
        $return_model = new \app\api\model\ProductOrderReturn();
        $admin = $this->admin;
        //dump($admin);
        $product_num = $product_model->where([
            [
                'uid','eq',$admin['uid']
            ]
        ])->count();//商品数
        $delivered = $order_model->where([
            [
                'uid','eq',$admin['uid']
            ],
            [
                'status','eq',1
            ]
        ])->count();//待发货

        $protection = $return_model->where([
            [
                'uid','eq',$admin['uid']
            ]
        ])->count();//售后
        $yesterday = $order_model->where([
            [
                'create_time','between',[strtotime(date('Y-m-d'))-86400,strtotime(date('Y-m-d'))]
            ],
            [
                'uid','eq',$admin['uid']
            ],
            [
                'status','not in',[-1,0]
            ],
        ])->count();//昨日订单
        $yesterday_money = $order_model->where([
            [
                'create_time','between',[strtotime(date('Y-m-d'))-86400,strtotime(date('Y-m-d'))]
            ],
            [
                'uid','eq',$admin['uid']
            ],
            [
                'status','not in',[-1,0]
            ],
        ])->sum('pay_money');//昨日金额

        return writeJson(200,[
            'product_num'=>$product_num,
            'delivered'=>$delivered,
            'protection'=>$protection,
            'yesterday'=>$yesterday,
            'yesterday_money'=>$yesterday_money,
        ]);

    }
    /**
     * 首页统计
     * @param Request $request
     */
    public function homeStatistics(Request $request){
        $post = $request->post();
        $order_model = new \app\api\model\ProductOrder();
        $user_model = new \app\admin\model\User();
        $shop_model = new \app\admin\model\Shop();
        $uidList = (new \app\admin\model\Shop())->where([
            ['status','eq',2],//
        ])->column("id");
        $where[] = ['uid','in',$uidList];
        $tobedelivered = $order_model->where([
            [
                'status','eq',1
            ],
            ['uid','in',$uidList]
        ])->count(1);//待发货
        $yesterday = $order_model->where([
            [
                'create_time','between',[strtotime(date('Y-m-d'))-86400,strtotime(date('Y-m-d'))]
            ],
            [
                'uid','in',$uidList
            ],
            [
                'status','not in',[-1,0]
            ]
        ])
            //->fetchSql(true)
            ->count();//昨日订单
        $today = $order_model->where([
            [
                'create_time','>',strtotime(date('Y-m-d'))
            ],
            [
                'uid','in',$uidList
            ],
            [
                'status','not in',[-1,0]
            ]
        ])->count();//今日订单
        $yesterday_money = $order_model->where([
            [
                'create_time','between',[strtotime(date('Y-m-d'))-86400,strtotime(date('Y-m-d'))],
            ],
            [
                'uid','in',$uidList
            ],
            [
                'status','not in',[-1,0]
            ]
        ])->sum('pay_money');//昨日金额
        $today_money = $order_model->where([
            [
                'create_time','>',strtotime(date('Y-m-d'))
            ],
            [
                'uid','in',$uidList
            ],
            [
                'status','not in',[-1,0]
            ]
        ])->sum('pay_money');//今日金额
        $order = [
            'tobedelivered'=>$tobedelivered,
            'yesterday'=>$yesterday,
            'today'=>$today,
            'yesterday_money'=>(string)$yesterday_money,
            'today_money'=>(string)$today_money,
        ];

        $ordinary = $user_model->where([
            [
                'status','=',1
            ],
            [
                'user_type','=',1
            ]
        ])->count();//普通用户
        $enterprise = $user_model->where([
            [
                'user_type','=',3
            ]
        ])->count();//企业用户
        $member = $user_model->where([
            [
                'user_type','in',[2,4]
            ]
        ])->count();//会员用户
        $yesterday = $user_model->where([
            [
                'create_time','between',[strtotime(date('Y-m-d'))-86400,strtotime(date('Y-m-d'))],
            ]
        ])->count();//昨日
        $today = $user_model->where([
            [
                'create_time','>',strtotime(date('Y-m-d'))
            ]
        ])->count();//今日

        $user = [
            'ordinary'=>$ordinary,
            'enterprise'=>$enterprise,
            'member'=>$member,
            'yesterday'=>$yesterday,
            'today'=>$today,
        ];
        $trader = $shop_model->where([
            [
                'type','=',3
            ],
//            [
//                'status','=',2
//            ]
        ])->count();//贸易商
        $brandshop = $shop_model->where([
            [
                'type','=',2
            ],
            [
                'status','=',2
            ]
        ])->count();//品牌店
        $online_merchant = $shop_model->where([
            [
                'type','=',1
            ],
            [
                'status','=',2
            ]
        ])->count();//线上商家
        $check = $shop_model->where([
            [
                'status','=',0
            ]
        ])->count();//审核中
        $today = $shop_model->where([
            [
                'create_time','>',strtotime(date('Y-m-d'))
            ]
        ])->count();//今日
        $shop = [
            'today'=>$today,
            'check'=>$check,
            'online_merchant'=>$online_merchant,
            'brandshop'=>$brandshop,
            'trader'=>$trader,
        ];

        $transaction = $order_model->where([
            [
                'status','in',[1,2]
            ],
            ['uid','in',$uidList]
        ])->sum('pay_money');
        return writeJson(200,[
            'order'=>$order,
            'user'=>$user,
            'shop'=>$shop,
            'transaction'=>$transaction,
            'allshop'=>$trader+$brandshop+$online_merchant
        ]);
    }
    /**
     * 用户列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function user_list(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $where = [];
        if(isset($post['min_money'])&&isset($post['max_money'])&&$post['min_money']!=""&&$post['max_money']!=""){
            $where[] = ['trade_money','between',[$post['min_money'],$post['max_money']]];
        }elseif (isset($post['min_money'])&&$post['min_money']!=""){
            $where[] = ['trade_money','egt',$post['min_money']];
        }elseif (isset($post['max_money'])&&$post['max_money']!=""){
            $where[] = ['trade_money','elt',$post['max_money']];
        }
        $where = addWhere($post,['phone'=>'','nickname'=>''],$where,2);//电话号和昵称查找
        $where = addWhere($post,['buy_card_number'=>'','user_type'=>''],$where,1);// 购卡次数和 用户类型
        $count = (new \app\admin\model\User())->getCount($where);
        $where['page'] = $post['page'];
        $dataList = (new \app\admin\model\User())->wechatList($where,"*","id desc",$post['page_number']);
        foreach ($dataList as $k=>$v){
            if($v["vip_time"] == null || $v["user_type"] == 1){ $dataList[$k]["vip_time"] = "-";}
            else{ $dataList[$k]["vip_time"] = date('Y-m-s h:i:s',$v["vip_time"]); }
        }
        $returnData = [
          'count'=>$count,
          'dataList'=>$dataList
        ];
        return writeJson(200,$returnData);
    }
    /**
     * 用户封停
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function user_check(Request $request){
        (new IdMustPositive())->goCheck();
        (new ActionMustPositiveValidate())->goCheck();
        $post = $request ->post();
        $res = (new \app\admin\model\User())->findOne([['id','eq',$post['id']]]);
        if(!$res){
            throw new NotFoundException(['msg'=>'用户不存在']);
        }
        $new = [
          'id'=>$post['id']
        ];
        if($post['action_type']=="check"){
            if(!in_array($post['check_status'],[1,2])){
                throw new FailedException(['msg'=>'用户状态不正确']);
            }
            $new['status'] = $post['check_status'];
        }
        $res = (new \app\admin\model\User())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'操作失败']);
        }
        //清理用户token
        $where["user_id"] = $post['id'];
        $res = (new UserToken())->fieldUpdate("delete_time",time(),"",["user_id"=>$post['id']]);
        if(!$res){
            throw new FailedException(['msg'=>'token操作失败']);
        }
        return writeJson(200);
    }
    /**
     * 修改用户会员状态
     * @param Request $request
     * @return \think\response\Json
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function user_edit(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request ->post();
        $where["id"] = $post["id"];
        $res = (new \app\admin\model\User())->fieldUpdate("user_type",$post["user_type"],"",$where);
        if(!$res){
            throw new NotFoundException(['msg'=>'操作失败']);
        }
        if($post["user_type"] > 1){
            $res = (new \app\admin\model\User())->fieldUpdate("vip_time",strtotime("+1 year"),"",$where);
            if(!$res){ throw new NotFoundException(['msg'=>'操作失败']);}
        }
        return writeJson(200);
    }
    /**
     * 用户企业申请审核列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function user_enterprise(Request $request){
        (new PageMustValidate())->goCheck();
         $post = $request->post();
         $where1 = [];
         $where  = [];
         $where1[] = ['status','in',[1,2]];
         $where[] =['om_user_enterprise.status','eq',1];
        if(isset($post['min_money'])&&isset($post['max_money'])&&$post['min_money']!=""&&$post['max_money']!=""){
            $where1[] = ['trade_money','between',[$post['min_money'],$post['max_money']]];
        }elseif (isset($post['min_money'])&&$post['min_money']!=""){
            $where1[] = ['trade_money','egt',$post['min_money']];
        }elseif (isset($post['max_money'])&&$post['max_money']!=""){
            $where1[] = ['trade_money','elt',$post['max_money']];
        }
        $where1 = addWhere($post,['phone'=>'','nickname'=>''],$where1,2);//电话号和昵称查找
        $where1 = addWhere($post,['buy_card_number'=>'','user_type'=>''],$where1,1);// 购卡次数和 用户类型
        $count = (new UserEnterprise())->getCountHasWhere("user",$where,$where1);
        $where['page'] = $post['page'];
        $dataList = (new UserEnterprise())->wechatListHasWhere("user",$where,$where1,"om_user_enterprise.*","om_user_enterprise.id desc",$post['page_number']);
        $returnData = [
            'count'=>$count,
            'dataList'=>$dataList
        ];
        return writeJson(200,$returnData);
    }
    /**
     * 企业审核的详情
     * @param Request $request
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function user_enterprise_detail(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $detail = (new UserEnterprise())->findOne([['id','eq',$post['id']]]);
        if(!$detail){
            throw new NotFoundException(['msg'=>'企业审核信息不存在']);
        }
        $detail['hand_id_card'] = imgUrlToAbsolute($detail['hand_id_card']);
        $detail['front_id_card'] = imgUrlToAbsolute($detail['front_id_card']);
        $detail['back_id_card'] = imgUrlToAbsolute($detail['back_id_card']);
        $detail['licence'] = imgUrlToAbsolute($detail['licence']);
        return writeJson(200,['detail'=>$detail]);
    }
    /**
     * 企业审核操作
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function user_enterprise_check(Request $request){
        (new IdMustPositive())->goCheck();
        (new ActionMustPositiveValidate())->goCheck();
        $post = $request->post();
        $detail = (new UserEnterprise())->findOneWith("user",[['id','eq',$post['id']]]);

        if(!$detail){
            throw new NotFoundException(['msg'=>'企业审核信息不存在']);
        }
        if($detail['status']!=1){
            throw new NotFoundException(['msg'=>'企业审核信息已审核']);
        }
        if($detail['user']['user_type']>2){
            throw new NotFoundException(['msg'=>'该用户已是企业身份无需审核']);
        }
        if($post['action_type']=="check"){
            $new = [
              'id'=>$post['id']
            ];
            if($post['check_status']==1){
                $new['status'] = 2;
            }elseif($post['check_status']==-1){
                $new['status'] = 3;
                $new['remark'] = isset($post['remark'])?$post['remark']:"";
            }
            Db::startTrans();
            $res = (new UserEnterprise())->dataUpdate($new);
            if(!$res){
                Db::rollback();
                throw new FailedException(['msg'=>'操作失败']);
            }else{
                if($post['check_status']==1){
                    $user_type =3;
                    //给用户转换身份
                    if($detail['user']['user_type']==2){
                        $user_type =4;
                    }
                    $res = (new \app\admin\model\User())->fieldUpdate("user_type",$user_type,$detail['user']['id']);
                    if(!$res){
                        Db::rollback();
                        throw new FailedException(['msg'=>'操作失败']);
                    }
                }
                Db::commit();
                return writeJson(200);
            }
        }
    }
    /**
     *  用户意见反馈列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function userFeedback(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $where = [];
        $where['page'] = $post['page'];
        $dataList = (new UserFeedback())->wechatListTotalWith("user",$where,"*","id desc",$post['page_number']);
        return writeJson(200,$dataList);
    }
    /**
     * 生成不重复的六位邀请码(大小写敏感)
     * @param int $user_id 用户ID   当用户ID为0时,为邀请码为空的全员生成邀请码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateInviteCode($user_id = 0){
        $UtilCommon = new UtilCommon();
        $userService = new \app\admin\model\User();
        $whereSql = "invite_code is null";
        if($user_id != 0){
            $whereSql .= "and id = ".$user_id;
        }
        //获取全员逐个遍历
        $userList = $userService->where($whereSql)->select()->toArray();
        foreach ($userList as $k=>$v){
            while (true){
                $randStr = $UtilCommon->GetRandStr();
                $where["invite_code"] = $randStr;
                if($userService->where($where)->count() == 0){
                    break;
                }
            }
            $userService->fieldUpdate("invite_code",$randStr,$v["id"]);
        }
        return writeJson(200,"修改成功");
    }
    /**
     * 获取不重复的六位邀请码 By UserId
     * @return bool
     */
    public function updateInviteCodeByUserId(){
        $UtilCommon = new UtilCommon();
        $userService = new \app\admin\model\User();
        while (true){
            $randStr = $UtilCommon->GetRandStr();
            $where["invite_code"] = $randStr;
            if($userService->where($where)->count() == 0){
                break;
            }
        }
        return $randStr;
    }
}
